const fs = require('fs')
/**
 * 1. 读取文件内容
 * 2. 写入文件内容
 * 3. 等待内容拼接
 * 4. 封装promise读取内容
 * 	modules: [
		{
			type: 'script',
			files: ['./src/static/js/index.js']
			//按照数组顺序 生成script标签放入到indexhtml中
		},
		{
			type: 'style',
			files: ['./src/static/css/common.css', './src/static/css/style.css']
			//按照数组顺序 生成style标签放入到indexhtml中
		}
	]
 */


class TemplateHtml {
  constructor() {
    this.state = {
      files: [
        {
          type: 'style',
          path: ['./src/static/css/index.css']
        },
        {
          type: 'script',
          path: ['./src/static/js/index.js']
        }
      ]
    }
  }

  // 读取文件内容
  readfile(src) {
    return new Promise((resolve, reject) => {
      fs.readFile(src, (err, data) => {
        resolve(data.toString())
      })
    })
  }
  // 获取文件内容
  async getInner(type, arr) {
    let text = `<${type}>`;
    for (let paths of arr) {
      text += await this.readfile(paths)
    }
    text += `</${type}>`
    return text
  }

  async writefile() {
    let html = await this.readfile('./src/index.html');
    for (let val of this.state.files) {
      let text = await this.getInner(val.type, val.path);
      html = html.replace(`<!-- ${val.type} -->`, text)
    }
    return html;
  }
}

const temHtml = new TemplateHtml()
temHtml.writefile().then(res => {
  fs.writeFile('./index.html', res, () => { })
})



// 题目讲解
// fs.readFile('./index.html', (err, data) => {
//   let res = data.toString().replace(/\<\!\-\- style \-\-\>/,
//     '<style>body{ background:red }</style>')

//   fs.writeFile('./index.html', res, (err, data) => {
//     console.log(data, 'data')
//   })
// })

// fs.writeFile('./index.html',
//   `<html>
//  <style>
//   body {
//     background: red;
//   } 
// </style>
//  <body></body>
// <html>`,
//   function (err, data) {
//     console.log(data)
//   }
// )